package com.manage;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.manage.http.AsyncHttpPost;
import com.manage.http.DefaultThreadPool;
import com.manage.http.RequestParameter;
import com.manage.http.RequestResultCallback;
import com.manage.http.RequestException;
import com.manage.model.Shop;
import com.manage.sharedpreferences.SPConfig;
import com.manage.util.ToastUtils;

import com.manage.base.BaseActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.Toast;

/**
 * 登录页面，登录成功保存用户信息，以后不用再次登录
 * @author liyoro
 *
 */
public class LoginActivity extends BaseActivity {

	private static String TAG = "LoginActivity";
	
	private AutoCompleteTextView mUin = null;
	private EditText mPassword = null;
	private View mLoginButton = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		/**
		 * 判断是否第一次登录
		 * 是：登录页面
		 * 否：直接跳转到首页
		 */
		if(accessToken.equals("0")) {
			setContentView(R.layout.activity_login);
		} else {
			String name = sp.getString(SPConfig.USERNAME, "");
			String pass = sp.getString(SPConfig.PASSWORD, "");
//			Log.i(TAG, name+";"+pass);
			this.login(name, pass);
		}
	}
	
	/**
	 * 保存用户信息
	 * @param name 用户名
	 * @param pass 用户密码
	 * @param token 用户访问令牌
	 */
	private void saveInfo(String name, String pass, String token, String shopID, String shopName) {
		sp.setString(SPConfig.USERNAME, name);
		sp.setString(SPConfig.PASSWORD, pass);
		sp.setString(SPConfig.ACCESSTOKEN, token);

		sp.setString(SPConfig.SHOPID, shopID);
		sp.setString(SPConfig.SHOPNAME, shopName);
	}

	/**
	 * 此handler主要是解决登录失败时，页面的toast提示
	 * 因为登录是通过队列异步进行的，不能在线程里处理LoginActivity里的界面
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) { 
			switch(msg.what) {
			case TIP: //登录失败提示
//				mUin.setText("");
//				mPassword.setText("");
				ToastUtils.show(LoginActivity.this.mContext, "登录失败，请检查用户名或者密码！", LoginActivity.this.getState());
				break;
			default:
				break;
			} 
		};
	};
	
	private View.OnClickListener butOnClick = new View.OnClickListener() {
		public void onClick(View paramView) {
			initDatas();
		}
	};

	@Override
	public String getLeftBtnName() {
		return null;
	}

	@Override
	public String getTitleName() {
		return "登录";
	}

	@Override
	public boolean showButton() {
		return false;
	}

	@Override
	public void initView() {
		this.mUin = (AutoCompleteTextView) findViewById(R.id.login_uin);
		this.mPassword = (EditText) findViewById(R.id.login_password);
		
		this.mLoginButton = findViewById(R.id.login_button);
		this.mLoginButton.setOnClickListener(butOnClick);
	}

	/**
	 * 登录
	 * @param name
	 * @param pass
	 */
	private void login(final String name, final String pass) {
		List<RequestParameter> parameterList = new ArrayList<RequestParameter>();
		parameterList.add(new RequestParameter("shopname", name));
		parameterList.add(new RequestParameter("pass", pass));
		
		AsyncHttpPost httpost = new AsyncHttpPost(null, LOGINURL, parameterList,
				new RequestResultCallback(){

				@Override
				public void onSuccess(Object o) {
					Log.i("HttpPostExample", "HttpPostExample  request  onSuccess result :"+((String)o).toString());
						
					try {
						JSONObject jsonTemp = new JSONObject(((String)o).toString());
						String return_info_fail = jsonTemp.get("signin_return").toString();
						boolean returnResult = Boolean.valueOf(return_info_fail);
						Log.i(TAG, ":"+returnResult);
							
						if(returnResult == false) {
							Message msg = new Message(); 
					        msg.what = TIP;
					        handler.sendMessage(msg);  //向Handler发送消息
						} else {
							Shop shop = new Shop();
							shop = Shop.setJson(((String)o).toString(), LoginActivity.this);
								
							// 保存用户信息
							saveInfo(name, pass, shop.getAccessToken(), shop.getShopID(), shop.getShopName());
								
							Intent mIntent = new Intent();
							mIntent.setClass(LoginActivity.this, ManageActivity.class);

						    Bundle mBundle = new Bundle();     
						    mBundle.putSerializable(SER_KEY, shop);     
						    mIntent.putExtras(mBundle);     
						        
							startActivity(mIntent);
							LoginActivity.this.finish();
						}
							
					} catch (JSONException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
					
				@Override
				public void onFail(Exception e) {
					Log.i("HttpPostExample", "HttpPostExample  request   onFail :"+((RequestException)e).getMessage());
						
					Message msg = new Message(); 
			        msg.what = TIP;
			        handler.sendMessage(msg);  //向Handler发送消息
				}
		});
		
		DefaultThreadPool.getInstance().execute(httpost);
		this.requestList.add(httpost);
	}
	
	@Override
	public void initDatas() {
		closeKeyboard();
		String str1 = this.mUin.getText().toString();
		String str2 = this.mPassword.getText().toString();
		
		if(str1.length() > 2 && str2.length() > 2) {
			this.login(str1, str2);
		} else {
			Toast.makeText(LoginActivity.this, "请输入用户名或者密码！", Toast.LENGTH_SHORT).show();
		}
	}
	
	/**
	 * 关闭软键盘
	 */
	private void closeKeyboard() {
		InputMethodManager localInputMethodManager = (InputMethodManager)getSystemService("input_method");
	    localInputMethodManager.hideSoftInputFromWindow(this.mUin.getWindowToken(), 0);
	    localInputMethodManager.hideSoftInputFromWindow(this.mPassword.getWindowToken(), 0);
	}
}
